from sqlalchemy.orm import Session
from models import PromptHistory
import time

def save_prompt(db: Session, prompt_text: str, created_by: str):
    # 获取当前最新版本号
    max_version = db.query(PromptHistory.version).order_by(PromptHistory.version.desc()).first()
    max_version = max_version[0] if max_version else 0
    
    # 插入新版本
    new_prompt = PromptHistory(
        prompt_text=prompt_text,
        version=max_version + 1,
        created_by=created_by,
        created_at=int(time.time())
    )
    db.add(new_prompt)
    db.commit()
    db.refresh(new_prompt)
    return {"message": "提示词保存成功", "version": max_version + 1}

def get_latest_prompt(db: Session):
    prompt = db.query(PromptHistory).order_by(PromptHistory.version.desc()).first()
    if prompt:
        return {
            "id": prompt.id,
            "prompt_text": prompt.prompt_text,
            "version": prompt.version,
            "created_by": prompt.created_by,
            "created_at": prompt.created_at
        }
    return {"error": "No prompts found"}

def get_prompts(db: Session):
    prompts = db.query(PromptHistory).order_by(PromptHistory.version.desc()).all()
    return [
        {
            "id": prompt.id,
            "prompt_text": prompt.prompt_text,
            "version": prompt.version,
            "created_by": prompt.created_by,
            "created_at": prompt.created_at
        }
        for prompt in prompts
    ]